import { useImperativeHandle, useRef } from 'react';

import { useInfiniteScroll } from 'ahooks';
import { Spin, Steps } from 'antd';
import cs from 'classnames';
import dayjs from 'dayjs';

import { store } from '@/store';

import { TimeSort } from '@/enum';
import { NoticeReadStatus } from '@/enum/notice';
import { sysMessageRecordPage } from '@/services/base/jichumokuaixiaoxijilujiekou';

import { alert_notice } from './detail-modal';
import styles from './index.module.scss';

export type ListInstance = ReturnType<
  typeof useInfiniteScroll<{
    total: number;
    page: number;
    list: BASE.SysMessageRecordEntity[];
  }>
>;

export type ListProps = {
  viewed?: NoticeReadStatus;
  listRef: React.Ref<ListInstance>;
};

const List: React.FC<ListProps> = ({ viewed, listRef }) => {
  const $list = useRef<HTMLDivElement>(null);
  const group = useRef<Record<number, string>>({});
  // {
  //   今天: 0,
  //   '2024-08-12': 2
  // }
  // 用户列表
  const noticeList = useInfiniteScroll<{
    total: number;
    page: number;
    list: BASE.SysMessageRecordEntity[];
  }>(
    async (query) => {
      const page = query ? query.page + 1 : 1;

      if (page === 1) {
        noticeList.mutate(undefined);
      }

      const pageQuery = {
        page,
        size: 20,
        timeSort: TimeSort.倒序,
        viewed
      } as ArgumentsType<typeof sysMessageRecordPage>[0];

      const res = await sysMessageRecordPage(pageQuery);

      const total = res?.data?.total || 0;
      const list = (query?.list || []).concat(res?.data?.records || []);

      group.current = {};
      const today = dayjs().format('YYYY-MM-DD');

      list.forEach((item, index) => {
        if (item.createTime) {
          // "2024-08-14 11:15:39"
          const time = dayjs(item.createTime, 'YYYY-MM-DD HH:mm:ss');
          let date = time.format('YYYY-MM-DD');

          if (date === today) {
            date = '今天';
          }

          if (Object.values(group.current).includes(date)) {
            return;
          }

          group.current[index] = date;
        }
      });

      return {
        list,
        total,
        page
      };
    },
    {
      isNoMore: (data) => {
        if (!data) {
          return false;
        }

        return data.list.length >= data.total;
      },
      target: $list,
      reloadDeps: [viewed]
    }
  );

  useImperativeHandle(listRef, () => noticeList);

  const onDetail = (item: BASE.SysMessageRecordEntity, index: number) => {
    alert_notice({
      data: item,
      onRead: () => {
        noticeList.data!.list[index].viewed = Number(NoticeReadStatus.已读);
        noticeList.mutate({
          ...noticeList.data
        } as typeof noticeList.data);
        store.getUnreadCount();
      }
    });
  };

  return (
    <div className={styles['notice-list']} ref={$list}>
      <Steps
        rootClassName={styles['steps']}
        progressDot
        current={noticeList.data?.list.length}
        direction="vertical"
        items={noticeList.data?.list.map((item, index) => {
          const time = dayjs(item.createTime, 'YYYY-MM-DD HH:mm:ss').format('HH:mm');

          return {
            className: cs(styles['step'], {
              [styles['read']]: String(item.viewed) === NoticeReadStatus.已读
            }),
            onClick: onDetail.bind(null, item, index),
            title: item.messageTitle,
            description: (
              <>
                {item.createBy} {item.messageType}
                <div className={styles['description']}>
                  {index in group.current ? (
                    <div className={styles['date']}>{group.current[index]}</div>
                  ) : undefined}
                  <div className={styles['time']}>{time}</div>
                </div>
              </>
            )
          };
        })}
      />
      {noticeList.noMore ? (
        <div className={styles['no-more']}>没有更多了</div>
      ) : (
        <div className={styles['loading']}>
          <Spin />
        </div>
      )}
    </div>
  );
};

export default List;
